package base

import (
	"errors"
	"fmt"

	"github.com/extrame/xls"
)

type XlsDataReader struct {
	filePath     string
	hasColHeader bool
	workBook     *xls.WorkBook
}

func NewXlsDataReader(filePath string, hasColHeader bool) (*XlsDataReader, error) {
	book, err := xls.Open(filePath, "utf-8")
	if err != nil {
		return nil, err
	}
	return &XlsDataReader{
		filePath:     filePath,
		hasColHeader: hasColHeader,
		workBook:     book,
	}, nil
}
func (x *XlsDataReader) GetSheetNames() ([]string, error) {
	count := x.workBook.NumSheets()
	sheetNames := make([]string, count, count)
	for i := 0; i < count; i++ {
		sheetNames[i] = x.workBook.GetSheet(i).Name
	}
	return sheetNames, nil
}
func (x *XlsDataReader) GetDataColumns(sheetName string) ([]string, error) {
	sheet, err := x.getSheet(sheetName)
	if err != nil {
		return nil, err
	}
	errInfo := ""
	if sheet.MaxRow == 0 {
		errInfo = fmt.Sprintf("指定的sheet[%s]没有数据！", sheetName)
		return nil, errors.New(errInfo)
	}
	row := sheet.Row(0)
	if row.LastCol() == 0 {
		errInfo = fmt.Sprintf("指定的sheet[%s]首行没有数据！", sheetName)
		return nil, errors.New(errInfo)
	}
	l := row.LastCol() + 1
	colNames := make([]string, 0, l)
	hasBlack := false
	if x.hasColHeader {
		for i := 0; i < l; i++ {
			cell := row.Col(i)
			if cell == "" {
				hasBlack = true
				continue
			} else {
				if hasBlack {
					errInfo = fmt.Sprintf("指定的sheet[%s]首行不允许合并单元格或者空单元格！", sheetName)
					return nil, errors.New(errInfo)
				}
				colNames = append(colNames, cell)
			}
		}
		return colNames, nil
	}
	for i := 0; i < l; i++ {
		colNames[i] = indexToColName(int(i))
	}
	return colNames, nil

}
func (x *XlsDataReader) ReadData(sheetName string) ([][]string, []int, error) {
	sheet, err := x.getSheet(sheetName)
	if err != nil {
		return nil, nil, err
	}
	errInfo := ""
	if sheet.MaxRow == 0 || (sheet.MaxRow == 1 && x.hasColHeader) {
		errInfo = fmt.Sprintf("指定的sheet[%s]没有数据！", sheetName)
		return nil, nil, errors.New(errInfo)
	}
	rowlen := sheet.MaxRow
	dataLen := rowlen
	i := 0
	k := 0
	if x.hasColHeader {
		i = 1
		dataLen--
	}
	datas := make([][]string, dataLen, dataLen)
	blankRowIndexs := make([]int, 0, 10)
	colNames, err := x.GetDataColumns(sheetName)
	if err != nil {
		return nil, nil, err
	}
	collen := len(colNames)
	for ; i < int(rowlen); i++ {
		datas[k] = make([]string, collen, collen)
		isAllBlank := true
		for j := 0; j < collen; j++ {
			cell := sheet.Row(i).Col(j)
			datas[k][j] = cell
			if cell != "" {
				isAllBlank = false
			}
		}
		if isAllBlank {
			blankRowIndexs = append(blankRowIndexs, int(k))
		}
		k++
	}
	return datas, blankRowIndexs, nil
}
func (x *XlsDataReader) getSheet(sheetName string) (*xls.WorkSheet, error) {
	count := x.workBook.NumSheets()
	for i := 0; i < count; i++ {
		sheet := x.workBook.GetSheet(i)
		if sheetName == sheet.Name {
			return sheet, nil
		}
	}
	errInfo := fmt.Sprintf("指定的sheet[%s]不存在！", sheetName)
	return nil, errors.New(errInfo)
}
